﻿// /////////////////////////////////////////////////////////////////////
// 
//  Codeplex JSAnalyse
//  Copyright (c) 2011
//  JSAnalyse.Core   AllowedDependenciesXmlReader.cs
// 
// /////////////////////////////////////////////////////////////////////
using System;
using System.Linq;
using System.Xml.Linq;
using JSAnalyse.Core.Interfaces;

namespace JSAnalyse.Core.Approver
{
    /// <summary>
    /// Standard implementation for the IAllowedDependencies interface.
    /// Checks based on the xml file "AllowedDependencies.xml" which javascript file references are allowed.
    /// </summary>
    internal class AllowedDependenciesXmlReader : IAllowedDependencies
    {
        /// <summary>
        /// Determines whether the specified dependeny file is allowd for specified file
        /// </summary>
        /// <param name="file">The base file</param>
        /// <param name="dependencyFile">The dependency file</param>
        /// <returns><c>true</c> if the specified file is allowed; otherwise, <c>false</c>.</returns>
        public bool IsAllowed(string file, string dependencyFile)
        {
            var document = XDocument.Load("AllowedDependencies.xml");
            return (from item in document.Descendants("file").Where(item =>
            {
                var xAttribute = item.Attribute("name");
                return xAttribute != null && !string.IsNullOrEmpty(xAttribute.Value) && file.EndsWith(xAttribute.Value, StringComparison.InvariantCultureIgnoreCase) ;
            }).Descendants()
            where !string.IsNullOrEmpty(item.Value) && dependencyFile.EndsWith(item.Value, StringComparison.InvariantCultureIgnoreCase)
            select item).Any();
        }
    }
}
